package com.cqw.auth.config.handler;

import com.cqw.auth.config.RedisClient;
import com.cqw.auth.enums.CodeEnum;
import com.cqw.auth.utils.JwtTokenUtil;
import com.cqw.auth.utils.ResultJSON;
import com.cqw.auth.utils.SecurityHandlerUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.TimeUnit;


/**
 * 登录成功
 * @Author cqw
 * @Date 2020年12月31日15:08:41
 */
@Slf4j
@Component
public class LoginSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Autowired
    RedisClient redisClient;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        Collection<? extends GrantedAuthority> s1 = authentication.getAuthorities();
        Object s2 = authentication.getCredentials();
        Object s3 = authentication.getDetails();
        Object s4 = authentication.getPrincipal();
        String tokenHeader = httpServletResponse.getHeader("token");

        // 去掉前缀 获取Token字符串
        String token = tokenHeader.replace(JwtTokenUtil.TOKEN_PREFIX, "");
        // 从Token中解密获取用户名
        String username = JwtTokenUtil.getUsername(token);
        // 从Token中解密获取用户角色
        String role = JwtTokenUtil.getUserRole(token);

        redisClient.setEx(JwtTokenUtil.REDIS_TOKEN + username + role ,token,JwtTokenUtil.EXPIRITION, TimeUnit.MICROSECONDS );
        SecurityHandlerUtil.responseHandler(httpServletResponse,new ResultJSON(CodeEnum.USER_LOGIN_SUCCESS));
    }
}
